<?php

use Phalcon\Mvc\Controller;

/**
 * 基控制器
 */
class ControllerBase extends Controller {

    protected function initialize() {
        
    }

    /**
     * 输出Json
     * @param array $arr
     */
    protected function echoJson($arr, $slash = true) {
        header('Content-Type: application/json; charset=utf-8');
        if (strpos(PHP_VERSION, '5.3') > -1) {
            // php 5.3-
            if($slash){
                 echo stripslashes(json_encode($arr));
             } else {
                 echo json_encode($arr);
             }
        } else {
            // php 5.4+
            if($slash){
                echo stripslashes(json_encode($arr, JSON_UNESCAPED_UNICODE));
            } else {
                echo json_encode($arr, JSON_UNESCAPED_UNICODE);
            }
        }
    }

    /**
     * 输出Json消息
     * @param type $code
     * @param type $msg
     */
    protected function echoMsg($code, $msg = '') {
        $this->echoJson(Array(
            'retcode' => $code,
            'retmsg' => $msg
        ));
        return true;
    }

    /**
     * 输出Json消息
     * @param type $code
     * @param type $msg
     */
    protected function echoSuccess() {
        $this->echoJson(Array(
            'retcode' => 0,
            'retmsg' => 'Success'
        ));
        return true;
    }

    /**
     * 输出错误消息
     * @param type $code
     * @param type $msg
     */
    protected function echoErrcode($errcode) {
        $this->echoJson(Array(
            'retcode' => $errcode[0],
            'retmsg' => NULL,
            'errmsg' => $errcode[1]
        ));
        return false;
    }

    /**
     * 控制器方法调用完毕，进行redis回收
     * @param type $dispatcher
     */
    public function afterExecuteRoute($dispatcher) {
        $redis = mRedis::get_instance();
        $redis->close();
    }

}
